package org.stone.project.zookeeper.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.stone.project.zookeeper.config.configProp.ZookeeperProp;

@Configuration
public class ZookeeperConfig {
    @Autowired
    private ZookeeperProp zookeeperProp;

    /**
     * 创建zookeeper客户端
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(CuratorFramework.class)
    public CuratorFramework zookeeperClient(){
        StringBuilder clients = new StringBuilder();
        String hostStr= null;
        if (zookeeperProp.getHost() != null){
            for (String host : zookeeperProp.getHost()) {
                clients.append(host);
                clients.append(",");
            }
            String tmpStr = clients.toString().trim();
            hostStr = clients.toString().trim().substring(0,tmpStr.length()-1);
        }else {
            hostStr = "127.0.0.1:2181";
        }

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(hostStr, retryPolicy);
        curatorFramework.start();
        return curatorFramework;
    }

    @Bean
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper objectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper;
    }
}
